package singleThreaded;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * URL Storage keeps track of all the links (visited & unvisited).
 * @author Son Pham
 * @version 1.0
 */
public class UrlStorage
{
  /**
   * The collection of visited pages.
   */
  private Map<String, String> my_visited_pages;
  
  /**
   * The collection of unvisited pages.
   * <p> This collection guarantees that these pages haven't been visited before.
   * <p> It doesn't guarantees that there are no duplicates in the collection.
   */
  private List<String> my_unvisited_pages;
  
  /**
   * Construct a UrlStorage object.
   */
  public UrlStorage()
  {
    my_visited_pages = new HashMap<String, String>();
    my_unvisited_pages = new LinkedList<String>();
  }
  
  /**
   * Add the URL to the collection of visited pages.
   * @param the_link The link.
   */
  public void addToVisitedPages(final String the_link)
  {
    my_visited_pages.put(the_link, "");
  }
  
  /**
   * 
   * @param the_link The link.
   * @return True if the link is already visited. False otherwise.
   */
  public boolean isAlreadyVisited(final String the_link)
  {
    return my_visited_pages.containsKey(the_link);
  }
  
  /**
   * 
   * @return The next unvisited page.
   */
  public String nextUnvisitedPage()
  {
    return ((LinkedList<String>) my_unvisited_pages).removeFirst();
  }
  
  /**
   * 
   * @return True if there is at least one unvisited page. False if there is none
   * unvisited page.
   */
  public boolean hasUnvisitedPage()
  {
    return !my_unvisited_pages.isEmpty();
  }
  
  /**
   * Add the link to the list of unvisited pages. Ensure that no duplicate links get added
   * to the list.
   * @param the_link The link.
   */
  public void addToUnvisitedPages(final String the_link)
  {
    //Check if the link is already in the list.
    if (!my_unvisited_pages.contains(the_link))
    {
      my_unvisited_pages.add(the_link);
    }    
  }
  
  /**
   * 
   * @return The next unvisited page in the list.
   */
  public String peekNextUnvisited()
  {
    return ((LinkedList<String>) my_unvisited_pages).peek();
  }
  
  /*
  public List<String> getListLinks()
  {
    return my_unvisited_pages;
  }*/
  
  /**
   * Print all the unvisited pages.
   */
  public void printUnvisitedPages()
  {
    final Iterator<String> iter = my_unvisited_pages.listIterator();
    while (iter.hasNext())
    {
      System.out.println(iter.next());
    }
  }
  
  /**
   * 
   * @return The total number of links which have been encountered so far.
   */
  public int getTotalLinks()
  {
    return my_visited_pages.size() + my_unvisited_pages.size();
  }
  
  public int numUnvisitedPages()
  {
    return my_unvisited_pages.size();
  }
}
